package net.wenku8.reader.view.rank

import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.snapshotFlow
import androidx.lifecycle.viewmodel.compose.viewModel
import net.wenku8.reader.state.StateRank
import net.wenku8.reader.ui.lite.LitePanel
import net.wenku8.reader.view.online.OnlineBookPreview
import androidx.compose.runtime.collectAsState


@Composable
fun RankDetail() {
    val rankDetailViewModel = viewModel<RankDetailViewModel>()
    LaunchedEffect(Unit) {
        rankDetailViewModel.initData()
    }
    val listState = rememberLazyListState()
    LaunchedEffect(listState) {
        snapshotFlow { listState.layoutInfo.visibleItemsInfo.lastOrNull() }
            .collect { lastVisibleItem ->
                if (lastVisibleItem != null && lastVisibleItem.index >= rankDetailViewModel.bookList.size - 1) {
                    // 当最后一个可见项是倒数第二个或更靠后时，触发加载更多
                    rankDetailViewModel.loadNextPage()
                }
            }
    }
    LitePanel(
        hostState = rankDetailViewModel.hostState,
        title = StateRank.title.collectAsState().value,
        backNav = true
    ) {
        Box{
            LazyColumn(state = listState){
                items(items = rankDetailViewModel.bookList) { book ->
                    OnlineBookPreview(book)
                }
            }
        }
    }

}
